package com.han.core.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.doudian.open.api.token.AccessTokenData;
import com.han.common.annotation.IgnoreToken;
import com.han.common.constant.CacheConstants;
import com.han.common.constant.HttpStatus;
import com.han.core.redis.RedisCache;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Resource
    RedisCache cache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            IgnoreToken methodAnnotation = handlerMethod.getMethodAnnotation(IgnoreToken.class);
            //如果有注解就跳过
            if (methodAnnotation != null) {
                return true;
            }
        }
        //token拦截器
        String token = request.getHeader("token");
        AccessTokenData cacheObject = cache.getCacheObject(CacheConstants.TOKEN_PREFIX + token);
        if (null == cacheObject) {
            //token失效
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", String.valueOf(HttpStatus.UNAUTHORIZED));
            jsonObject.put("msg", "token is unused");
            response.getWriter().write(jsonObject.toString());
            return false;
        }
        //todo 是否判断店铺状态，是否在有效时间内
        request.setAttribute("accessToken", cacheObject);
        return true;
    }
}
